const bluebird = require('bluebird');


const redis = require('redis');


const config = require('../config/config');


const RDS_PORT = config.redis.port;


const RDS_HOST = config.redis.host;


const RDS_PWD = config.redis.pwd;


const RDS_OPTS = {
  auth_pass: RDS_PWD,
  db: 1,
};


const client = redis.createClient(RDS_PORT, RDS_HOST, RDS_OPTS);

const prefix = 'NODE_IM';

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

client.on('connect', () => {
  console.log('redis is connect');
});
client.on('ready', () => {
  console.log('redis is already');
});
client.on('error', (err) => {
  console.log(`redis error ${err}`);
});

module.exports.fetch = function (key) {
  console.log(` fetch redis token--->${prefix}${key}`);
  return client.getAsync(prefix + key);
};
module.exports.set = function (key, object) {
  return client.setAsync(prefix + key, object).then(() => client.expireAsync(prefix + key, 2 * 24 * 60 * 60));
};
module.exports.expire = function (key, time) {
  return client.expireAsync(prefix + key, time || 20);
};
module.exports.del = function (key) {
  return client.delAsync(prefix + key);
};
